<template>
  <view class="menu-item" :class="{ selected: (item.isSelected && !hasChildren) }">
    <!-- 主菜单项 -->
    <view class="menu-title" @click="toggle">
      {{ item.title }}
      <span v-if="hasChildren" class="arrow" :class="{ 'open': item.isOpen }">▲</span>
    </view>
    <!-- 子菜单 -->
    <view v-if="hasChildren" v-show="item.isOpen" class="submenu">
      <MenuItem v-for="(subItem, subIndex) in item.children" :key="subIndex" :item="subItem" 
		@cancleAll="cancleAll(subItem)"/>
    </view>
  </view>
</template>

<script setup lang="ts">
import { computed, ref } from 'vue';

interface Props {
  item: ListType;
}
import{ListType} from '../types/types'
import { useCommonStore } from '../stores/useCommonStore';
import { log } from 'console';

const props = defineProps<Props>();
const emit = defineEmits(['cancleAll']);
const commonStore = useCommonStore();
const hasChildren = computed(() => !!props.item.children && props.item.children.length > 0);

const isSubMenuOpen = ref<Record<number, boolean>>({});
const cancleAll = (nowItem:ListType)=>{
	// 递归取消所有子项的选中状态
	nowItem?.children?.forEach((item)=>{
		item.isSelected = false;
		if(item.children) {
			cancleAll(item);
		}
	});
	// 向父组件发送事件，清除其他项的选中状态
	emit('cancleAll', nowItem);
}
const toggle = () => {
	if (hasChildren.value) {
		props.item.isOpen = !props.item.isOpen;
		// 点击有子项的菜单时，取消该项的选中状态
		props.item.isSelected = false;
		
	} else {
		// 点击无子项的菜单项时，发送事件清除其他所有项的选中状态
		emit('cancleAll', props.item);
		// 设置当前项为选中状态
		props.item.isSelected = true;
		
		commonStore.select(props.item.id);
		
	}
};

const toggleSubMenu = (subIndex: number) => {
	isSubMenuOpen.value[subIndex] = !isSubMenuOpen.value[subIndex];
	
};
</script>

<style scoped lang="less">
.menu-item {
	&.selected {
	    background-color: rgb(231,172,179);
	}
	height: auto; /* 动态高度 */
	line-height: 2rem;
	padding: 0.3rem;
	margin-bottom: 0.1rem;
	text-align: left;
	white-space: nowrap;
	font-size: 0.9rem;
  .menu-title {
    display: flex;
    justify-content: space-between;
    align-items: center;
    cursor: pointer;
    
    .arrow {
      transition: transform 0.3s ease;
    }
    
    .open {
      transform: rotate(180deg);
    }
  }

  .submenu {
    margin-top: 0.5rem;
    padding-left: 0.1rem;
    // background-color: lightpink;
  }
}
</style>